﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using TyMES.ViewModel.Record.ScanMaterialSNVMs;
using TyMES.Model.Record;
using TyMES.Communication.Request;
using TyMES.Communication;
using static TyMES.Communication.Request.RepairRequest;
using TyMES.TemporaryClass;


namespace TyMES.Controllers
{
    [Area("Record")]
    [AuthorizeJwtWithCookie]
    [ActionDescription("扫码绑定SN")]
    [ApiController]
    [Route("api/ScanMaterialSN")]
	public partial class ScanMaterialSNController : BaseApiController
    {
        [ActionDescription("Sys.Search")]
        [HttpPost("Search")]
		public IActionResult Search(ScanMaterialSNSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<ScanMaterialSNListVM>(passInit: true);
                vm.Searcher = searcher;
                return Content(vm.GetJson());
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public ScanMaterialSNVM Get(string id)
        {
            var vm = Wtm.CreateVM<ScanMaterialSNVM>(id);
            return vm;
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("Add")]
        public IActionResult Add(ScanMaterialSNVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoAdd();
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("Edit")]
        public IActionResult Edit(ScanMaterialSNVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoEdit(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<ScanMaterialSNBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }


        [ActionDescription("Sys.Export")]
        [HttpPost("ExportExcel")]
        public IActionResult ExportExcel(ScanMaterialSNSearcher searcher)
        {
            var vm = Wtm.CreateVM<ScanMaterialSNListVM>();
            vm.Searcher = searcher;
            vm.SearcherMode = ListVMSearchModeEnum.Export;
            return vm.GetExportData();
        }

        [ActionDescription("Sys.CheckExport")]
        [HttpPost("ExportExcelByIds")]
        public IActionResult ExportExcelByIds(string[] ids)
        {
            var vm = Wtm.CreateVM<ScanMaterialSNListVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = new List<string>(ids);
                vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
            }
            return vm.GetExportData();
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<ScanMaterialSNImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(ScanMaterialSNImportVM vm)
        {
            if (vm!=null && (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData()))
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm?.EntityList?.Count ?? 0);
            }
        }

        [ActionDescription("批量绑定")]
        [HttpPost("BindOneBatch")]
        public ActionResult BindOneBatch(ScanMaterialRequest request)
        {
            try
            {
                List<ScanMaterialSN> scanMaterials = new List<ScanMaterialSN>();
                string batchCode = request.WarehouseCode+DateTime.Now.ToString("yyyyMMddHHmmssss");
                foreach(var bom in request.MaterialBOM)
                {
                    ScanMaterialSN scanMaterial = new ScanMaterialSN();
                    scanMaterial.assemblyMaterialSN = request.MaterialBindings[bom.AssemblyMaterialCode];
                    scanMaterial.assemblyMaterialCode = bom.AssemblyMaterialCode;
                    scanMaterial.assemblyMaterialName = bom.AssemblyMaterialName;
                    scanMaterial.batchCode = batchCode;
                    scanMaterial.BindTime = DateTime.Now;
                    DealUnbind(scanMaterial.assemblyMaterialSN);
                    scanMaterials.Add(scanMaterial);
                }
                DC.Set<ScanMaterialSN>().AddRange(scanMaterials);
                DC.SaveChanges();
                return Ok(new ResponseBase(true, "扫码绑定完成"));
            }
            catch (Exception ex)
            {
                return Ok(new ResponseBase(false, $"扫码绑定异常:{ex.Message}"));
            }
        
        }

        public ResponseBase DealUnbind(string AssemblyMaterialSN)
        {
            try
            {
                var bindinfo = DC.Set<MaterialBindRecord>().Where(x => x.AssemblyMaterialSn == AssemblyMaterialSN).FirstOrDefault();
                if (bindinfo == null)
                {
                    return new ResponseBase(true,"");
                }
                bindinfo.AssemblyMaterialSn = bindinfo.AssemblyMaterialSn + "unbind";
                DC.SaveChanges();
                return new ResponseBase(true, "");
            }
            catch (Exception ex)
            {
                return new ResponseBase(false, $"转台解绑失败:{ex.Message}");
            }
        }


    }
}
